package com.github.iot.activity;

import android.Manifest;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;

import com.github.iot.R;
import com.github.iot.dao.CommonDaoUtils;
import com.github.iot.dao.DaoUtilsStore;
import com.github.iot.entity.SystemSetting;
import com.github.iot.entity.User;
import com.github.iot.utils.ActivityUtils;
import com.github.iot.utils.BarUtils;
import com.github.iot.utils.FastJsonUtils;
import com.github.iot.utils.KeyboardUtils;
import com.github.iot.utils.SharedPreferencesUtils;
import com.github.iot.utils.ToastUtils;
import com.github.iot.view.dialogs.fragment.ProgressDialogFragment;
import com.google.android.material.textfield.TextInputEditText;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 登录Activity
 *
 * @Author: 梁声洪
 * @Date: 2019/12/06 9:14
 * @Version: v1.0.0
 */
public class LoginActivity extends AppCompatActivity {

    private static final String[] permissionsGroup = new String[]{
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    @BindView(R.id.et_username)
    TextInputEditText mUsername;

    @BindView(R.id.et_password)
    TextInputEditText mPassword;

    @BindView(R.id.btn_login)
    Button mLogin;

    @BindView(R.id.tv_name)
    TextView mTvName;

    private boolean isPermission = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarUtils.setStatusBarColor(this, R.color.colorPrimaryDark);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initUser();
        checkPermission();
    }

    /**
     * 检查权限
     */
    private void checkPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        Observable.timer(200, TimeUnit.MILLISECONDS)
                .compose(rxPermissions.ensureEachCombined(permissionsGroup))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(permission -> isPermission = permission.granted);
    }

    @OnClick({R.id.btn_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                KeyboardUtils.hideSoftInput(LoginActivity.this);
                userLogin();
                break;
            default:
                break;
        }
    }

    /**
     * 用户登录
     */
    private void userLogin() {
        String username = mUsername.getText().toString();
        String password = mPassword.getText().toString();

        if (null == username || "".equals(username)) {
            ToastUtils.warning("账号不能为空");
            return;
        }

        if (null == password || "".equals(password)) {
            ToastUtils.warning("密码不能为空");
            return;
        }

        DialogFragment dialog = ProgressDialogFragment.createBuilder(this, getSupportFragmentManager())
                .setMessage("正在登录...")
                .setRequestCode(1)
                .setCancelable(false)
                .show();

        Observable.timer(2000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(t -> userLogin(username, password, dialog));
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @param dialog
     */
    private void userLogin(String username, String password, DialogFragment dialog) {
        CommonDaoUtils<User> commonDao = DaoUtilsStore.getInstance().getUserDaoUtils();
        String sql = "where username = ?";
        String[] conditions = new String[]{username};
        List<User> list = commonDao.queryByNativeSql(sql, conditions);

        if (list.size() == 0) {
            ToastUtils.error("账号不存在", 3000);
            dialog.dismiss();
            mUsername.setText("");
            mPassword.setText("");
            KeyboardUtils.showSoftInput(this, mUsername);
            return;
        }

        User user = list.get(0);
        if (!password.equals(user.getPassword())) {
            ToastUtils.error("密码输入错误", 3000);
            dialog.dismiss();
            mPassword.setText("");
            mPassword.setFocusable(true);
            KeyboardUtils.showSoftInput(this, mPassword);
            return;
        }

        SharedPreferencesUtils.putString(this, "iot_login_user", FastJsonUtils.obj2JsonStr(user));
        ActivityUtils.skipActivityAndFinishAll(this, MainActivity.class);
    }

    private void initUser() {
        CommonDaoUtils<User> commonDao = DaoUtilsStore.getInstance().getUserDaoUtils();
        String sql = "where username = ?";
        String[] conditions = new String[]{"hbhx456"};
        List<User> list1 = commonDao.queryByNativeSql(sql, conditions);
        if (list1.size() == 0) {
            User user = new User();
            user.setNickname("智能展柜");
            user.setUsername("hbhx456");
            user.setPassword("hbhx456");
            user.setType(1);
            commonDao.insert(user);
        }

        CommonDaoUtils<SystemSetting> settingDao = DaoUtilsStore.getInstance().getSystemSettingDaoUtils();
        List<SystemSetting> list2 = settingDao.queryAll();
        if (list2.size() == 0) {
            SystemSetting setting = new SystemSetting();
            setting.setName("智能控制展柜");
            // setting.setName("陕西历史博物馆");
            settingDao.insert(setting);

            mTvName.setText(setting.getName());
        } else {
            SystemSetting setting = list2.get(0);
            mTvName.setText(setting.getName());
        }
    }

}